<template>
  <div class="file-processor">
    <!-- 文件上传区域 -->
    <el-card class="card">
      <template #header>
        <h2>文件上传</h2>
      </template>

      <el-upload
          class="upload-demo"
          drag
          action=""
          :auto-upload="false"
          @change="handleFileChange"
          :file-list="fileList"
          accept=".txt"
          :limit="1"
          @exceed="handleExceed"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          拖放文件到此处，或<em>点击上传</em>
        </div>
        <div class="el-upload__hint">
          仅支持TXT文件，最大支持30MB
        </div>
      </el-upload>

      <div v-if="selectedFile" class="file-info">
        <p>已选择文件: {{ selectedFile.name }}</p>
        <p>文件大小: {{ formatFileSize(selectedFile.size) }}</p>
      </div>

      <div class="btn-group">
        <el-button
            type="primary"
            :disabled="!selectedFile || isProcessing"
            @click="handleProcess('encrypt')"
        >
          <el-icon v-if="isProcessing && processType === 'encrypt'"><loading /></el-icon>
          加密文件
        </el-button>
        <el-button
            type="success"
            :disabled="!selectedFile || isProcessing"
            @click="handleProcess('decrypt')"
        >
          <el-icon v-if="isProcessing && processType === 'decrypt'"><loading /></el-icon>
          解密文件
        </el-button>
        <el-button
            type="warning"
            :disabled="!selectedFile"
            @click="clearFile"
        >
          清除文件
        </el-button>
      </div>
    </el-card>

    <!-- 处理结果区域 -->
    <el-card class="card" v-if="showResult">
      <template #header>
        <h2>处理结果</h2>
      </template>

      <div v-if="isProcessing" class="processing-indicator">
        <el-icon class="is-loading" size="50"><loading /></el-icon>
        <p style="margin-top: 16px;">正在{{ processType === 'encrypt' ? '加密' : '解密' }}文件，请稍候...</p>
      </div>

      <div v-else>
        <p>文件处理完成！</p>

        <div class="btn-group">
          <el-button
              type="primary"
              @click="downloadResult"
          >
            <el-icon><download /></el-icon>
            下载文件
          </el-button>
          <el-button
              type="info"
              @click="togglePreview"
          >
            <el-icon><view /></el-icon>
            {{ showPreview ? '隐藏预览' : '预览内容' }}
          </el-button>
        </div>

        <div v-if="showPreview" class="preview-container">
          <pre>{{ fileContent }}</pre>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { encryptFile, decryptFile } from '../utils/api';
import { UploadFilled, Loading, Download, View } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

// 文件相关状态
const fileList = reactive([]);
const selectedFile = ref(null);
const isProcessing = ref(false);
const processType = ref('');
const showResult = ref(false);
const processedFile = ref(null);
const fileContent = ref('');
const showPreview = ref(false);
const response = ref(null);

// 处理文件选择
const handleFileChange = (file) => {
  // 验证文件类型
  if (file.name.lastIndexOf('.txt') === -1) {
    ElMessage.error('请上传TXT格式的文件');
    fileList.splice(0, 1);
    return;
  }

  // 验证文件大小 (30MB)
  if (file.size > 30 * 1024 * 1024) {
    ElMessage.error('文件大小不能超过30MB');
    fileList.splice(0, 1);
    return;
  }

  selectedFile.value = file.raw;
  showResult.value = false;
};

// 处理文件超出限制
const handleExceed = () => {
  ElMessage.warning('只能上传一个文件');
};

// 清除已选文件
const clearFile = () => {
  fileList.length = 0;
  selectedFile.value = null;
  showResult.value = false;
  processedFile.value = null;
  fileContent.value = '';
};

// 处理文件加密/解密
const handleProcess = async (type) => {
  if (!selectedFile.value) return;

  isProcessing.value = true;
  processType.value = type;
  showResult.value = true;

  try {
    // 根据类型调用不同的API
    response.value = type === 'encrypt'
        ? await encryptFile(selectedFile.value)
        : await decryptFile(selectedFile.value);

    if (type === 'encrypt') {
      // 加密：响应是二进制数据
      processedFile.value = response.value.data;
      // 读取文件内容用于预览
      const reader = new FileReader();
      reader.onload = (e) => {
        fileContent.value = e.target.result;
      };
      reader.readAsText(processedFile.value);
    } else {
      // 解密：响应是文本内容
      fileContent.value = response.value.data;
      // 创建Blob对象用于下载
      processedFile.value = new Blob([response.value.data], { type: 'text/plain' });
    }

    ElMessage.success(`${type === 'encrypt' ? '加密' : '解密'}成功`);
  } catch (error) {
    console.error('处理文件失败:', error);
    ElMessage.error(error.response?.data?.message || `${type === 'encrypt' ? '加密' : '解密'}失败，请重试`);
  } finally {
    isProcessing.value = false;
  }
};

// 下载处理后的文件
const downloadResult = () => {
  if (!processedFile.value) return;

  // 从响应头获取文件名
  const contentDisposition = response.value?.headers['content-disposition'];
  let filename = processType.value === 'encrypt'
      ? `encrypted_${selectedFile.value.name}`
      : `decrypted_${selectedFile.value.name}`;

  if (contentDisposition) {
    const matches = /filename\*?=UTF-8''([^;]+)/i.exec(contentDisposition);
    if (matches && matches[1]) {
      filename = decodeURIComponent(matches[1]);
    }
  }

  // 创建下载链接
  const url = window.URL.createObjectURL(new Blob([processedFile.value]));
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', filename);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  window.URL.revokeObjectURL(url);
};

// 切换预览显示状态
const togglePreview = () => {
  showPreview.value = !showPreview.value;
};

// 格式化文件大小显示
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};
</script>